package com.ruoyi.web.controller.common;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.wf.captcha.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{

    @Autowired
    private RedisCache redisCache;
    
    // 验证码类型
    @Value("${ruoyi.captchaType}")
    private String captchaType;
    
    @Autowired
    private ISysConfigService configService;
    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode() {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        ajax.put("captchaOnOff", captchaOnOff);
        if (!captchaOnOff)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String capStr = null, code = null;

        // 生成验证码
        if ("png".equals(captchaType))
        {
            // png类型
            SpecCaptcha captcha = new SpecCaptcha(100, 38,4);
            code = captcha.text();  // 获取验证码的字符
            capStr = captcha.toBase64();

        }else if ("gif".equals(captchaType)){
            // gif类型
            GifCaptcha captcha = new GifCaptcha(100, 38,4);
            capStr = captcha.toBase64();
            code = captcha.text();  // 获取验证码的字符
        }else if("cngif".equals(captchaType)){
            // 中文gif类型
            ChineseGifCaptcha captcha = new ChineseGifCaptcha(100, 38,4);
            capStr = captcha.toBase64();
            code = captcha.text();  // 获取验证码的字符
        }else if("cn".equals(captchaType)){
            // 中文类型
            ChineseCaptcha captcha = new ChineseCaptcha(100, 38,4);
            capStr = captcha.toBase64();
            code = captcha.text();  // 获取验证码的字符
        }else if("math".equals(captchaType)){
            // 算术类型
            ArithmeticCaptcha captcha = new ArithmeticCaptcha(100, 38,2);
            //captcha.getArithmeticString();  // 获取运算的公式：3+2=?
            capStr = captcha.toBase64();
            code = captcha.text();  // 获取运算的结果：5
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        ajax.put("uuid", uuid);
        ajax.put("img", capStr);
        return ajax;
    }
}
